/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.SalesForecast;

import merlion.mrp.ppm.pojo.LongHolder;
import helper.SalesChartItemOnePeriod;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import merlion.common.util.Consts;
import merlion.mrp.ppm.entity.HistoricalInd;
import merlion.mrp.ppm.entity.IndivForecast;
import merlion.mrp.ppm.entity.IndustryInd;
import merlion.mrp.ppm.entity.SalesForecast;
import merlion.mrp.ppm.entity.StaticInd;
import merlion.mrp.ppm.session.SalesForecastingSessionLocal;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Zhang Ying
 */
@ManagedBean(name = "sfEditManagerBean")
@ViewScoped
public class SalesForecastEditManagerBean {

    @EJB
    private SalesForecastingSessionLocal salesForecastSession;
    private ArrayList<String> labels;
    private SalesForecast selectedSF;
    // present information
    private ArrayList<ArrayList<Long>> previousTotalSales;
    private ArrayList<ArrayList<Long>> previousPromotion;
    private ArrayList<Long> prevIndustryTotDmd;
    private ArrayList<Integer> staticPeriods;
    private ArrayList<Integer> allStaticPeriods;
    private ArrayList<Integer> periodiocities;
    private ArrayList<ArrayList<Long>> allActualDemands;
    private ArrayList<ArrayList<Long>> allDesDemand;
    private ArrayList<ArrayList<Long>> allDesDemandFromActual;
    private ArrayList<ArrayList<Double>> allDesFactor;
    private ArrayList<ArrayList<Double>> allEstimatedDesFactor;
    private ArrayList<ArrayList<Double>> lgResult; // 4 * 2 (level, trend)
    private ArrayList<Double> level; //
    private ArrayList<Double> trend; //4
    private double inputtedIndustryYoY;
    private double inputtedIndustryMarketShare;
    // for c:forEach
    private ArrayList<Integer> counter;
    private ArrayList<Integer> counterForProduct;
    // for dialog selection of variables
    private Integer selectedHistoricalId;
    private Integer selectedIndustryId;
    private Integer selectedStaticId;
    private ArrayList<HistoricalInd> histYoYs;
    private ArrayList<ArrayList<LongHolder>> humanAdjusts;
    private ArrayList<ArrayList<LongHolder>> promotions;

    /** Creates a new instance of SalesForecastEditManagerBean */
    public SalesForecastEditManagerBean() {
        counter = new ArrayList<Integer>();
        for (int i = 0; i < 6; i++) {
            counter.add(new Integer(i));
        }
        counterForProduct = new ArrayList<Integer>();
        for (int i = 0; i < 4; i++) {
            counterForProduct.add(new Integer(i));
        }
//        for (int i = 0; i < 4; i++) {
//            histYoYs.add(new HistoricalInd());
//            ArrayList<LongHolder> temp1 = new ArrayList<LongHolder>();
//            ArrayList<LongHolder> temp2 = new ArrayList<LongHolder>();
//            for (int j = 0; j < 6; j++) {
//                temp1.add(new LongHolder());
//                temp2.add(new LongHolder());
//            }
//            humanAdjusts.add(temp1);
//            promotions.add(temp2);
//        }
    }

    // all setters and getters
    public ArrayList<String> getLabels() {
        labels = new ArrayList<String>();
        if (getSelectedSF().getStartPeriodMonth() < 7) {
            labels.add(Consts.JAN);
            labels.add(Consts.FEB);
            labels.add(Consts.MAR);
            labels.add(Consts.APR);
            labels.add(Consts.MAY);
            labels.add(Consts.JUN);
        } else {
            labels.add(Consts.JUL);
            labels.add(Consts.AUG);
            labels.add(Consts.SEP);
            labels.add(Consts.OCT);
            labels.add(Consts.NOV);
            labels.add(Consts.DEC);
        }
        return labels;
    }

    public void setLabels(ArrayList<String> labels) {
        this.labels = labels;
    }

    public SalesForecast getSelectedSF() {
        if (selectedSF == null) {
            SalesForecast sf = (SalesForecast) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(SalesForecastMgmtManagerBean.EDIT_SF);
            if (sf != null) {
                selectedSF = sf;
            }
            // populate values
            histYoYs = new ArrayList<HistoricalInd>();
            humanAdjusts = new ArrayList<ArrayList<LongHolder>>();
            promotions = new ArrayList<ArrayList<LongHolder>>();
            for (int i = 0; i < 4; i++) {
                HistoricalInd hi = new HistoricalInd();
                hi.setYoy(selectedSF.returnProductIndivForecast(i).getHistoricalSF().getYoy());
                histYoYs.add(hi);
                ArrayList<LongHolder> temp1 = new ArrayList<LongHolder>();
                ArrayList<LongHolder> temp2 = new ArrayList<LongHolder>();
                for (int j = 0; j < 6; j++) {
                    LongHolder lh1 = new LongHolder();
                    LongHolder lh2 = new LongHolder();
                    lh1.setL(selectedSF.returnProductIndivForecast(i).getHumanAdjustList().get(j).getLongValue());
                    lh2.setL(selectedSF.returnProductIndivForecast(i).getPromotionList().get(j).getLongValue());
                    temp1.add(lh1);
                    temp2.add(lh2);
                }
                humanAdjusts.add(temp1);
                promotions.add(temp2);
            }
        }
        return selectedSF;
    }

    public void setSelectedSF(SalesForecast selectedSF) {
        this.selectedSF = selectedSF;
    }

    public ArrayList<Integer> getCounter() {
        return counter;
    }

    public void setCounter(ArrayList<Integer> counter) {
        this.counter = counter;
    }

    public ArrayList<Integer> getCounterForProduct() {
        return counterForProduct;
    }

    public void setCounterForProduct(ArrayList<Integer> counterForProduct) {
        this.counterForProduct = counterForProduct;
    }

    // setters and getters for information
    public ArrayList<ArrayList<Long>> getPreviousTotalSales() {
        int selectedYear = selectedSF.getStartPeriodYear();
        boolean isFirstHalf;
        if (selectedSF.getStartPeriodMonth() < 7) {
            isFirstHalf = true;
        } else {
            isFirstHalf = false;
        }
        if (previousTotalSales == null) {
            previousTotalSales = salesForecastSession.getPreviousTotalSales(new Long(selectedYear), isFirstHalf);
        }
        return previousTotalSales;
    }

    public void setPreviousTotalSales(ArrayList<ArrayList<Long>> previousTotalSales) {
        this.previousTotalSales = previousTotalSales;
    }

    public ArrayList<ArrayList<Long>> getPreviousPromotion() {
        int selectedYear = selectedSF.getStartPeriodYear();
        boolean isFirstHalf;
        if (selectedSF.getStartPeriodMonth() < 7) {
            isFirstHalf = true;
        } else {
            isFirstHalf = false;
        }
        if (previousPromotion == null) {
            previousPromotion = salesForecastSession.getPreviousPromotion(new Long(selectedYear), isFirstHalf);
        }
        return previousPromotion;
    }

    public void setPreviousPromotion(ArrayList<ArrayList<Long>> previousPromotion) {
        this.previousPromotion = previousPromotion;
    }

    public ArrayList<Long> getPrevIndustryTotDmd() {
        int selectedYear = selectedSF.getStartPeriodYear();
        boolean isFirstHalf;
        if (selectedSF.getStartPeriodMonth() < 7) {
            isFirstHalf = true;
        } else {
            isFirstHalf = false;
        }
        if (prevIndustryTotDmd == null) {
            prevIndustryTotDmd = salesForecastSession.getPreviousIndustryTotalDemand(new Long(selectedYear), isFirstHalf);
        }
        return prevIndustryTotDmd;
    }

    public void setPrevIndustryTotDmd(ArrayList<Long> prevIndustryTotDmd) {
        this.prevIndustryTotDmd = prevIndustryTotDmd;
    }

    public ArrayList<Integer> getStaticPeriods() {
        int selectedYear = selectedSF.getStartPeriodYear();
        boolean isFirstHalf;
        if (selectedSF.getStartPeriodMonth() < 7) {
            isFirstHalf = true;
        } else {
            isFirstHalf = false;
        }
        if (staticPeriods == null) {
            staticPeriods = salesForecastSession.getStaticPeriods(new Long(selectedYear), isFirstHalf);
        }
        return staticPeriods;
    }

    public void setStaticPeriods(ArrayList<Integer> staticPeriods) {
        this.staticPeriods = staticPeriods;
    }

    public ArrayList<Integer> getAllStaticPeriods() {
        if (allStaticPeriods == null) {
            Timestamp currentTime = selectedSF.getDateCreated();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            int currentYear = Integer.valueOf(sdf.format(currentTime));
            sdf = new SimpleDateFormat("MM");
            int currentMonth = Integer.valueOf(sdf.format(currentTime));
            allStaticPeriods = salesForecastSession.getAllStaticPeriods(currentYear, currentMonth);
        }
        return allStaticPeriods;
    }

    public void setAllStaticPeriods(ArrayList<Integer> allStaticPeriods) {
        this.allStaticPeriods = allStaticPeriods;
    }

    public long roundToLong(Double d) {
        return Math.round(d);
    }

    public ArrayList<ArrayList<Long>> getAllActualDemands() {
        if (allStaticPeriods == null) {
            getAllStaticPeriods();
        }
        if (allActualDemands == null) {
            Timestamp currentTime = selectedSF.getDateCreated();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            int currentYear = Integer.valueOf(sdf.format(currentTime));
            sdf = new SimpleDateFormat("MM");
            int currentMonth = Integer.valueOf(sdf.format(currentTime));
            allActualDemands = salesForecastSession.getAllProductsActualDemands(currentYear, currentMonth);
        }
        return allActualDemands;
    }

    public void setAllActualDemands(ArrayList<ArrayList<Long>> allActualDemands) {
        this.allActualDemands = allActualDemands;
    }

    public ArrayList<ArrayList<Long>> getAllDesDemand() {
        if (trend == null || level == null) {
            getTrend();
            getLevel();
        }
        if (allDesDemand == null) {
            allDesDemand = salesForecastSession.getAllProductDesDemand(allStaticPeriods, trend, level);
        }
        return allDesDemand;
    }

    public ArrayList<ArrayList<Long>> resetAllDesDemand() {
        allDesDemand = salesForecastSession.getAllProductDesDemand(allStaticPeriods, trend, level);
        return allDesDemand;
    }

    public void setAllDesDemand(ArrayList<ArrayList<Long>> allDesDemand) {
        this.allDesDemand = allDesDemand;
    }

    public ArrayList<ArrayList<Double>> getAllDesFactor() {
        if (allDesDemand == null) {
            getAllDesDemand();
        }
        if (allDesFactor == null) {
            allDesFactor = salesForecastSession.getAllProductDesFactor(allDesDemand, allActualDemands);
        }
        return allDesFactor;
    }

    public ArrayList<ArrayList<Double>> resetAllDesFactor() {
        allDesFactor = salesForecastSession.getAllProductDesFactor(allDesDemand, allActualDemands);
        return allDesFactor;
    }

    public void setAllDesFactor(ArrayList<ArrayList<Double>> allDesFactor) {
        this.allDesFactor = allDesFactor;
    }

    public ArrayList<ArrayList<Double>> getAllEstimatedDesFactor() {
        if (allDesFactor == null) {
            getAllDesFactor();
        }
        if (allEstimatedDesFactor == null) {
            allEstimatedDesFactor = salesForecastSession.getAllProductEstimDesFactor(allDesFactor, getPeriodiocities());
        }
        return allEstimatedDesFactor;
    }

    public ArrayList<ArrayList<Double>> resetAllEstimatedDesFactor() {
        allEstimatedDesFactor = salesForecastSession.getAllProductEstimDesFactor(allDesFactor, getPeriodiocities());
        return allEstimatedDesFactor;
    }

    public void setAllEstimatedDesFactor(ArrayList<ArrayList<Double>> allEstimatedDesFactor) {
        this.allEstimatedDesFactor = allEstimatedDesFactor;
    }

    public ArrayList<ArrayList<Double>> getLgResult() {
        if (allDesDemandFromActual == null) {
            getAllDesDemandFromActual();
        }
        if (lgResult == null) {
            lgResult = salesForecastSession.getLinearRegressResultLnT(allDesDemandFromActual, allStaticPeriods);
            getLevel();
            getTrend();
        }
        return lgResult;
    }

    public ArrayList<ArrayList<Double>> resetLgResult() {
        lgResult = salesForecastSession.getLinearRegressResultLnT(allDesDemandFromActual, allStaticPeriods);
        return lgResult;
    }

    public void setLgResult(ArrayList<ArrayList<Double>> lgResult) {
        this.lgResult = lgResult;
    }

    public ArrayList<Double> getLevel() {
        if (lgResult == null) {
            getLgResult();
        }
        if (level == null) {
            level = new ArrayList<Double>();
            for (int i = 0; i < 4; i++) {
                ArrayList<Double> temp = lgResult.get(i);
                level.add(temp.get(0));
            }
        }
        return level;
    }

    public ArrayList<Double> resetLevel() {
        level = new ArrayList<Double>();
        for (int i = 0; i < 4; i++) {
            ArrayList<Double> temp = lgResult.get(i);
            level.add(temp.get(0));
        }
        return level;
    }

    public void setLevel(ArrayList<Double> level) {
        this.level = level;
    }

    public ArrayList<Double> getTrend() {
        if (lgResult == null) {
            getLgResult();
        }
        if (trend == null) {
            trend = new ArrayList<Double>();
            for (int i = 0; i < 4; i++) {
                ArrayList<Double> temp = lgResult.get(i);
                trend.add(temp.get(1));
            }
        }
        return trend;
    }

    public ArrayList<Double> resetTrend() {
        trend = new ArrayList<Double>();
        for (int i = 0; i < 4; i++) {
            ArrayList<Double> temp = lgResult.get(i);
            trend.add(temp.get(1));
        }
        return trend;
    }

    public void setTrend(ArrayList<Double> trend) {
        this.trend = trend;
    }

    public ArrayList<ArrayList<Long>> getAllDesDemandFromActual() {
        if (allActualDemands == null) {
            getAllActualDemands();
        }
        if (allDesDemandFromActual == null) {
            allDesDemandFromActual = salesForecastSession.getAllProductDesDemandFromActual(allActualDemands, getPeriodiocities());
        }
        return allDesDemandFromActual;
    }

    public ArrayList<ArrayList<Long>> resetAllDesDemandFromActual() {
        allDesDemandFromActual = salesForecastSession.getAllProductDesDemandFromActual(allActualDemands, getPeriodiocities());
        return allDesDemandFromActual;
    }

    public void setAllDesDemandFromActual(ArrayList<ArrayList<Long>> allDesDemandFromActual) {
        this.allDesDemandFromActual = allDesDemandFromActual;
    }

    public ArrayList<Integer> getPeriodiocities() {
        periodiocities = new ArrayList<Integer>();
        for (int i = 0; i < 4; i++) {
            periodiocities.add(selectedSF.returnProductIndivForecast(i).getStaticSF().getPeriodiocity());
        }
        return periodiocities;
    }

    public void setPeriodiocities(ArrayList<Integer> periodiocities) {
        this.periodiocities = periodiocities;
    }

    public boolean renderedDesDFromAcutal(Long item) {
        if (item > -1) {
            return true;
        } else {
            return false;
        }
    }

    public List<String> completeCreatedMethod() {
        List<String> result = new ArrayList<String>();
        result.add(Consts.FORECAST_METHOD_HISTORICAL);
        result.add(Consts.FORECAST_METHOD_INDUSTRY);
        result.add(Consts.FORECAST_METHOD_STATIC);
        return result;
    }

    public double returnEstimDesFactorByProductNPeriod(Integer period, int i) {
        return getAllEstimatedDesFactor().get(i).get(period % (getPeriodiocities().get(i)));
    }

    public double getInputtedIndustryMarketShare() {
        for (int i = 0; i < 4; i++) {
            String type = getSelectedSF().returnProductIndivForecast(i).getCreatedType();
            if (type != null && type.equals(Consts.FORECAST_METHOD_INDUSTRY)) {
                inputtedIndustryMarketShare = selectedSF.returnProductIndivForecast(i).getIndustrySF().getMarketShare();
            }
        }
        return inputtedIndustryMarketShare;
    }

    public void setInputtedIndustryMarketShare(double inputtedIndustryMarketShare) {
        this.inputtedIndustryMarketShare = inputtedIndustryMarketShare;
    }

    public double getInputtedIndustryYoY() {
        for (int i = 0; i < 4; i++) {
            String type = selectedSF.returnProductIndivForecast(i).getCreatedType();
            if (type != null && type.equals(Consts.FORECAST_METHOD_INDUSTRY)) {
                inputtedIndustryYoY = selectedSF.returnProductIndivForecast(i).getIndustrySF().getYoy();
            }
        }
        return inputtedIndustryYoY;
    }

    public void setInputtedIndustryYoY(double inputtedIndustryYoY) {
        this.inputtedIndustryYoY = inputtedIndustryYoY;
    }

    public void resetStaticComputations() {
        getPeriodiocities();
        resetAllDesDemandFromActual();
        resetLgResult();
        resetLevel();
        resetTrend();
        resetAllDesDemand();
        resetAllDesFactor();
        resetAllEstimatedDesFactor();
    }

    public void selectIndustrySF(Integer count) {
        setSelectedIndustryId(count);
    }

    public void selectHistoricalSF(Integer count) {
        for (int i = 0; i < 4; i++) {
            histYoYs.get(i).setYoy(selectedSF.returnProductIndivForecast(i).getHistoricalSF().getYoy());
        }
        setSelectedHistoricalId(count);
    }

    public void selectStaticSF(Integer count) {
        setSelectedStaticId(count);
    }

    public Integer getSelectedHistoricalId() {
        return selectedHistoricalId;
    }

    public void setSelectedHistoricalId(Integer selectedHistoricalId) {
        this.selectedHistoricalId = selectedHistoricalId;
    }

    public Integer getSelectedIndustryId() {
        return selectedIndustryId;
    }

    public void setSelectedIndustryId(Integer selectedIndustryId) {
        this.selectedIndustryId = selectedIndustryId;
    }

    public Integer getSelectedStaticId() {
        return selectedStaticId;
    }

    public void setSelectedStaticId(Integer selectedStaticId) {
        this.selectedStaticId = selectedStaticId;
    }

    public ArrayList<HistoricalInd> getHistYoYs() {
        return histYoYs;
    }

    public void setHistYoYs(ArrayList<HistoricalInd> histYoYs) {
        this.histYoYs = histYoYs;
    }

    // click and then update the individual form's base projection and final value
    public void updateBPNCalculateFinal(Integer selectedProduct) {
        IndivForecast indiv = selectedSF.returnProductIndivForecast(selectedProduct);
        // validations
        if (indiv.getCreatedType() == null || indiv.getCreatedType().equals("")) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product " + returnProductName(selectedProduct),
                    "Please choose the method for base projection."));
            return;
        }
        // validation: check promotions >=0
        for (int i = 0; i < 6; i++) {
            if (promotions.get(selectedProduct).get(i).getL() < 0) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product " + returnProductName(selectedProduct),
                        "You promotion cannot be negative"));
                return;
            }
        }
        // calculate bp and final
        for (int j = 0; j < 6; j++) {
            System.out.println("Testing: method for creation: " + indiv.getCreatedType());
            if (indiv.getCreatedType().equals(Consts.FORECAST_METHOD_HISTORICAL)) {
                // historical
                indiv.getBaseProjectionSelected().get(j).setLongValue(
                        roundToLong((1 + indiv.getHistoricalSF().getYoy()) * (previousTotalSales.get(selectedProduct).get(j) - previousPromotion.get(selectedProduct).get(j))));
            } else if (indiv.getCreatedType().equals(Consts.FORECAST_METHOD_INDUSTRY)) {
                // industry
                IndustryInd industry = indiv.getIndustrySF();
                indiv.getBaseProjectionSelected().get(j).setLongValue(
                        roundToLong(industry.getProudctShare() * industry.getMarketShare() * (1 + industry.getYoy()) * prevIndustryTotDmd.get(j)));
            } else {
                // static
                int period = staticPeriods.get(j);
                indiv.getBaseProjectionSelected().get(j).setLongValue(
                        roundToLong((trend.get(selectedProduct) * period + level.get(selectedProduct)) * returnEstimDesFactorByProductNPeriod(period, selectedProduct)));
            }
            indiv.getHumanAdjustList().get(j).setLongValue(humanAdjusts.get(selectedProduct).get(j).getL());
            indiv.getPromotionList().get(j).setLongValue(promotions.get(selectedProduct).get(j).getL());
            indiv.getFinalValues().get(j).setLongValue(indiv.getBaseProjectionSelected().get(j).getLongValue()
                    + indiv.getHumanAdjustList().get(j).getLongValue() + indiv.getPromotionList().get(j).getLongValue());
        }
    }

    // inside dialog for historical, calculate using the yoy
    public void calculateHistorical(Integer selectedHistorical) {
        // do validations
        RequestContext requestContext = RequestContext.getCurrentInstance();
        if (histYoYs.get(selectedHistorical) == null || histYoYs.get(selectedHistorical).equals("")) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product" + returnProductName(selectedHistorical),
                    "Please input valid growth rate."));
            requestContext.addCallbackParam("isValid", false);
            return;
        }
        requestContext.addCallbackParam("isValid", true);
    }

    // update yoy to the real yoy
    public void confirmHistorical(Integer selectedHistorical) {
        // do validations
        if (histYoYs.get(selectedHistorical) == null || histYoYs.get(selectedHistorical).equals("")) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product" + returnProductName(selectedHistorical),
                    "Please input valid growth rate."));
            return;
        }
        selectedSF.returnProductIndivForecast(selectedHistorical).getHistoricalSF().setYoy(histYoYs.get(selectedHistorical).getYoy());
    }

    // inside dialog for static, using periodicity to calculate
    public void calculateStatic(Integer selectedStatic) {
        // do validations
        RequestContext requestContext = RequestContext.getCurrentInstance();
        IndivForecast indiv = selectedSF.returnProductIndivForecast(selectedStatic);
        StaticInd staticInd = indiv.getStaticSF();
        if (staticInd.getPeriodiocity() > 12 || staticInd.getPeriodiocity() < 1) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product" + returnProductName(selectedStatic),
                    "Please input valid periodicity (0<p<12)."));
            requestContext.addCallbackParam("isValid", false);
            return;
        }
        // update static data
        resetStaticComputations();
        requestContext.addCallbackParam("isValid", true);
    }

    public ArrayList<ArrayList<LongHolder>> getHumanAdjusts() {

        return humanAdjusts;
    }

    public void setHumanAdjusts(ArrayList<ArrayList<LongHolder>> humanAdjusts) {
        this.humanAdjusts = humanAdjusts;
    }

    public ArrayList<ArrayList<LongHolder>> getPromotions() {
        return promotions;
    }

    public void setPromotions(ArrayList<ArrayList<LongHolder>> promotions) {
        this.promotions = promotions;
    }

    // input all the variables in dialog and click calculate -> will call this method
    public void updateIndustryData(ActionEvent event) {
        double sum = 0;
        RequestContext requestContext = RequestContext.getCurrentInstance();
        for (int i = 0; i < 4; i++) {
            IndivForecast indiv = selectedSF.returnProductIndivForecast(i);
            IndustryInd industrySF = indiv.getIndustrySF();
            if (inputtedIndustryMarketShare > 1.0 || inputtedIndustryMarketShare < 0.0) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Your market share should be within the range of 0 to 1 for product" + i, "Your market share should be within the range of 0 to 1"));
                requestContext.addCallbackParam("isValid", false);
                return;
            } else {
                sum += industrySF.getProudctShare();
            }
        }
        if (Math.abs(sum - 1.0) > SalesForecastManagerBean.THRESHOLD) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful", "The total of product share should be 1"));
            requestContext.addCallbackParam("isValid", false);
            return;
        }
        // input data if not validation fail
        for (int i = 0; i < 4; i++) {
            IndivForecast indiv = selectedSF.returnProductIndivForecast(i);
            IndustryInd industrySF = indiv.getIndustrySF();
            industrySF.setMarketShare(inputtedIndustryMarketShare);
            industrySF.setYoy(inputtedIndustryYoY);
        }
        requestContext.addCallbackParam("isValid", true);
    }

    public void calculateAll(ActionEvent event) {
        // check validations
        for (int i = 0; i < 4; i++) {
            IndivForecast indiv = selectedSF.returnProductIndivForecast(i);
            StaticInd staticInd = indiv.getStaticSF();
            if (indiv.getCreatedType() == null || indiv.getCreatedType().equals("")) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product" + returnProductName(i),
                        "Please choose the method for base projection."));
                return;
            }
            if (staticInd.getPeriodiocity() > 12 || staticInd.getPeriodiocity() < 1) {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product" + returnProductName(i),
                        "Please input valid periodicity (0<p<12)."));
                return;
            }
        }
        // check whether promotion bigger than 0
        for (int j = 0; j < 4; j++) {
            for (int i = 0; i < 6; i++) {
                if (promotions.get(j).get(i).getL() < 0) {
                    FacesContext.getCurrentInstance().addMessage(null,
                            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful for product " + returnProductName(j),
                            "You promotion cannot be negative"));
                    return;
                }
            }
        }
        // update final by bp, promo, human adjust
        for (int i = 0; i < 4; i++) {
            IndivForecast indiv = selectedSF.returnProductIndivForecast(i);
            for (int j = 0; j < 6; j++) {
                System.out.println("Testing: method for creation: " + indiv.getCreatedType());
                if (indiv.getCreatedType().equals(Consts.FORECAST_METHOD_HISTORICAL)) {
                    // historical
                    indiv.getBaseProjectionSelected().get(j).setLongValue(
                            roundToLong((1 + indiv.getHistoricalSF().getYoy()) * (previousTotalSales.get(i).get(j) - previousPromotion.get(i).get(j))));
                } else if (indiv.getCreatedType().equals(Consts.FORECAST_METHOD_INDUSTRY)) {
                    // industry
                    IndustryInd industry = indiv.getIndustrySF();
                    indiv.getBaseProjectionSelected().get(j).setLongValue(
                            roundToLong(industry.getProudctShare() * industry.getMarketShare() * (1 + industry.getYoy()) * prevIndustryTotDmd.get(j)));
                } else {
                    // static
                    int period = staticPeriods.get(j);
                    indiv.getBaseProjectionSelected().get(j).setLongValue(
                            roundToLong((trend.get(i) * period + level.get(i)) * returnEstimDesFactorByProductNPeriod(period, i)));
                }
                indiv.getHumanAdjustList().get(j).setLongValue(humanAdjusts.get(i).get(j).getL());
                indiv.getPromotionList().get(j).setLongValue(promotions.get(i).get(j).getL());
                indiv.getFinalValues().get(j).setLongValue(indiv.getBaseProjectionSelected().get(j).getLongValue()
                        + indiv.getHumanAdjustList().get(j).getLongValue() + indiv.getPromotionList().get(j).getLongValue());
            }
        }
    }

    public String returnProductName(Integer pid) {
        if (pid.equals(0)) {
            return Consts.ProductType.BAR_A.getText();
        } else if (pid.equals(1)) {
            return Consts.ProductType.BAR_B.getText();
        } else if (pid.equals(2)) {
            return Consts.ProductType.BAR_C.getText();
        } else {
            return Consts.ProductType.BAR_D.getText();
        }
    }

    // for reference table and figures
    public Collection<SalesChartItemOnePeriod> returnActDemandFigure() {
        ArrayList<SalesChartItemOnePeriod> result = new ArrayList<SalesChartItemOnePeriod>();
        for (int i = 0; i < getAllActualDemands().get(0).size(); i++) {
            result.add(new SalesChartItemOnePeriod(String.valueOf(i + 1), allActualDemands.get(0).get(i), allActualDemands.get(1).get(i), allActualDemands.get(2).get(i), allActualDemands.get(3).get(i)));
        }
        return result;
    }

    // save edition
    public String confirmEdit() {
        if (salesForecastSession.saveEditedSalesForecast(selectedSF)) {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove(SalesForecastMgmtManagerBean.EDIT_SF);
            return getRedirectPath(Consts.EDIT_SALES_FORECAST_PATH + "Confirm");
        } else {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful",
                    "not able to persist into the database"));
            return null;
        }
    }

    // for general purpose
    private String getRedirectPath(String path) {
        return path + "?faces-redirect=true";
    }
}
